# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time

# from jms.dm.dm_transit_violation_detail_to_dt import jms_dm__dm_transit_violation_detail_to_dt
from utils.operators.rich_sql_sensor import RichSqlSensor


#doris表名
doris_table = "dm_transit_violation_detail_to_dt"
#label名
label = f"{doris_table}_{int(time())}"
#hive中表名
hive_table = "dm_transit_violation_detail_to_dt"
#hdfs文件路径
hdfs_path ="hdfs://{{var.value.hadoop_namespace}}/dw/hive/jms_dm.db/external/"
timeout = timedelta(hours=2).seconds
#判断当天分区是否存在
file_path = f'"{hdfs_path}{hive_table}/dt={{{{ execution_date | cst_ds }}}}/*/*"'
partition_lists = []
path_lists = []
for i in range(0, 7):
    if i == 0:
        partition_lists.append("p{{ execution_date | cst_ds_nodash }}")
        path_lists.append(file_path)
    else:
        partition_lists.append("p{{ execution_date | date_add(-" + str(i) + ") | cst_ds_nodash }}")
        path_lists.append(f'"{hdfs_path}{hive_table}/dt={{{{ execution_date | date_add(-{i}) | cst_ds }}}}/*/*"')

partition_str = ",".join(partition_lists)
path_str = ",".join(path_lists[::-1])
doris_jms_dm__dm_transit_violation_detail_to_dt = RichSqlSensor(
    task_id='doris_jms_dm__dm_transit_violation_detail_to_dt',
    pool='broker_load_pool',
    email=['jokic.wang@jtexpress.com'],
    task_concurrency=1,
    conn_id='new_doris',
    pre_sql=f"""
                 TRUNCATE TABLE jms_dm.{doris_table} PARTITION ({partition_str});
                 LOAD LABEL jms_dm.{label} (
                     DATA INFILE({path_str})
                     INTO TABLE {doris_table}
                     FORMAT AS 'PARQUET'(
                         waybill_no
                        ,trace_line
                        ,sender_center_arri_time
                        ,send_time_2
                        ,arrival_time_2
                        ,sender_center_code
                        ,sender_center_simple_name
                        ,sender_center_name
                        ,receiver_center_code
                        ,receiver_center_simple_name
                        ,receiver_center_name
                        ,center_code_1
                        ,center_simple_name_1
                        ,center_name_1
                        ,center_code_2
                        ,center_simple_name_2
                        ,center_name_2
                        ,center_code_3
                        ,center_simple_name_3
                        ,center_name_3
                        ,pre_shipment_no
                        ,pre_mileage
                        ,next_mileage
                        ,package_total_volume
                        ,route_code
                        ,route_name
                        ,standby_route_code
                        ,standby_route_name
                        ,real_all_line_code
                        ,real_all_line
                        ,real_road_agent_code
                        ,real_line_code
                        ,real_line
                        ,is_match_main
                        ,is_match_standby
                        ,main_next_code
                        ,main_next_name
                        ,main_next_next_code
                        ,main_next_next_name
                        ,standby_next_code
                        ,standby_next_name
                        ,standby_next_next_code
                        ,standby_next_next_name
                        ,is_tmp_shipment
                        ,is_violation
                        ,is_wrong
                        ,is_miss
                        ,is_dispatch
                        ,is_sub
                        ,is_violation_detail
                        ,data_type
                        ,apply_time
                        ,arrival_time_later
                        ,arrival_time_early
                        ,detail_type
                        ,sender_center_dt
                        ,arrival_center_dt
                        ,etl_process_time
                        ,date_time
                 )
                 columns from path as (dt)
                 set(
                     date_time                    =  date_time
                    ,detail_type                  =  detail_type
                    ,sender_center_dt             =  sender_center_dt
                    ,arrival_center_dt            =  arrival_center_dt
                    ,waybill_no                   =  waybill_no
                    ,pre_shipment_no              =  pre_shipment_no
                    ,trace_line                   =  trace_line
                    ,center_code_1                =  center_code_1
                    ,center_code_2                =  center_code_2
                    ,center_code_3                =  center_code_3
                    ,is_violation                 =  is_violation
                    ,is_violation_detail          =  is_violation_detail
                    ,sender_center_arri_time      =  sender_center_arri_time
                    ,send_time_2                  =  send_time_2
                    ,arrival_time_2               =  arrival_time_2
                    ,sender_center_code           =  sender_center_code
                    ,sender_center_simple_name    =  sender_center_simple_name
                    ,sender_center_name           =  sender_center_name
                    ,receiver_center_code         =  receiver_center_code
                    ,receiver_center_simple_name  =  receiver_center_simple_name
                    ,receiver_center_name         =  receiver_center_name
                    ,center_simple_name_1         =  center_simple_name_1
                    ,center_name_1                =  center_name_1
                    ,center_simple_name_2         =  center_simple_name_2
                    ,center_name_2                =  center_name_2
                    ,center_simple_name_3         =  center_simple_name_3
                    ,center_name_3                =  center_name_3
                    ,pre_mileage                  =  pre_mileage
                    ,next_mileage                 =  next_mileage
                    ,package_total_volume         =  package_total_volume
                    ,route_code                   =  route_code
                    ,route_name                   =  route_name
                    ,standby_route_code           =  standby_route_code
                    ,standby_route_name           =  standby_route_name
                    ,real_all_line_code           =  real_all_line_code
                    ,real_all_line                =  real_all_line
                    ,real_road_agent_code         =  real_road_agent_code
                    ,real_line_code               =  real_line_code
                    ,real_line                    =  real_line
                    ,is_match_main                =  is_match_main
                    ,is_match_standby             =  is_match_standby
                    ,main_next_code               =  main_next_code
                    ,main_next_name               =  main_next_name
                    ,main_next_next_code          =  main_next_next_code
                    ,main_next_next_name          =  main_next_next_name
                    ,standby_next_code            =  standby_next_code
                    ,standby_next_name            =  standby_next_name
                    ,standby_next_next_code       =  standby_next_next_code
                    ,standby_next_next_name       =  standby_next_next_name
                    ,is_tmp_shipment              =  is_tmp_shipment
                    ,is_wrong                     =  is_wrong
                    ,is_miss                      =  is_miss
                    ,is_dispatch                  =  is_dispatch
                    ,is_sub                       =  is_sub
                    ,data_type                    =  data_type
                    ,apply_time                   =  apply_time
                    ,arrival_time_later           =  arrival_time_later
                    ,arrival_time_early           =  arrival_time_early
                    ,etl_process_time             =  etl_process_time
                   )
                 )
                 WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
                 PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dm WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dm WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )

# doris_jms_dm__dm_transit_violation_detail_to_dt << [
#     jms_dm__dm_transit_violation_detail_to_dt
# ]
